最後最後我們來加上我們最後的機制,開始的按鈕以及結束時重新開始的按鈕。
在場景加上按鈕,提供使用者決定合適要開始。
結束的時候也可以共用同一顆按鈕,改變一下文案即可。
這邊有一個新的機制,需要透過設定 setInteractive() 來觸發他的互動事件,就可以加上滑鼠事件了。
在 update 中先讓遊戲物理引擎室暫停的狀態,在使用者按下開始按鈕時,再將物理引擎開啟,並且將按鈕隱藏。
// 遊戲是否進行的 trigger
let startGame = false;
function create(){
  ...
  
  button = this.add
    .text(200, 400, "遊戲開始", {
      fontSize: "40px",
      fill: "#eeeeee",
      backgroundColor: "#00db00",
      padding: { x: 15, y: 15 },
    })
    .setInteractive()
    .on("pointerdown", () => {
      toggleGame();
      this.physics.resume();
      button.visible = false;
    });
    button.setDepth(1);
}
function update(){
  if (!startGame) {
    this.physics.pause();
  }
  ...
  
}
function toggleGame() {
  startGame = !startGame;
}
遊戲結束時,顯示按鈕,並且修改文案,按下按鈕的事件改變成設置一個黑幕等待整個遊戲重新啟動。
function update(){
  ...
  
  if ((player.y > 766 && !player.body.touching.down) || life <= 0) {
    this.physics.pause();
    player.setTint(0xff0000);
    player.setFrame(0);
    button.setText("重新開始");
    button.setBackgroundColor("#ee0000");
    button.on("pointerdown", () => {
      let black = this.add.rectangle(300, 400, 600, 800, "0x000000");
      black.setDepth(2);
      this.scene.restart();
    });
    button.visible = true;
  }
  ...
  
}
就可以看到我們的遊戲畫面更完整了XD

YA~~~~~~~~~~ 我們終於完成了我們的下樓梯,真是累QQ
Phaser Game 2020鐵人賽